package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.vo.DesignStatisticsQueryVO;
import com.ruoyi.system.domain.vo.DesignStatisticsVO;
import com.ruoyi.system.mapper.DesignStatisticsMapper;
import com.ruoyi.system.service.IDesignStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DesignStatisticsServiceImpl implements IDesignStatisticsService {

    @Autowired
    private DesignStatisticsMapper designStatisticsMapper;

    @Override
    public DesignStatisticsVO getDesignStatistics(DesignStatisticsQueryVO query) {
        DesignStatisticsVO result = new DesignStatisticsVO();

        // 1. 总设计项目数
        Integer totalDesignCount = designStatisticsMapper.selectTotalDesignCount(query);
        result.setTotalDesignCount(totalDesignCount != null ? totalDesignCount : 0);

        // 2. 平均方案耗时
        BigDecimal avgDesignDays = designStatisticsMapper.selectAvgDesignDays(query);
        result.setAvgDesignDays(avgDesignDays != null ? avgDesignDays.setScale(1, RoundingMode.HALF_UP) : BigDecimal.ZERO);

        // 3. 总出图量
        Integer totalImageCount = designStatisticsMapper.selectTotalImageCount(query);
        result.setTotalImageCount(totalImageCount != null ? totalImageCount : 0);

        // 4. 素材平均使用率
        Map<String, Long> materialUsageMap = designStatisticsMapper.selectMaterialUsageAndProjectCount(query);
        if (materialUsageMap != null && materialUsageMap.get("projectCount") != null && materialUsageMap.get("projectCount") > 0L) {
            Long materialUsageCount = materialUsageMap.get("materialUsageCount") != null ? materialUsageMap.get("materialUsageCount") : 0L;
            Long projectCount = materialUsageMap.get("projectCount");
            BigDecimal usageRate = new BigDecimal(materialUsageCount)
                    .divide(new BigDecimal(projectCount), 2, RoundingMode.HALF_UP);
            result.setAvgMaterialUsageRate(usageRate);
        } else {
            result.setAvgMaterialUsageRate(BigDecimal.ZERO);
        }

        // 5. 设计师耗时统计
        List<DesignStatisticsVO.DesignerTimeStatsVO> designerTimeStats = designStatisticsMapper.selectDesignerTimeStats(query);
        // 处理空值
        if (designerTimeStats != null) {
            designerTimeStats.forEach(stat -> {
                if (stat.getAvgDays() != null) {
                    stat.setAvgDays(stat.getAvgDays().setScale(1, RoundingMode.HALF_UP));
                } else {
                    stat.setAvgDays(BigDecimal.ZERO);
                }
                if (stat.getFastestDays() == null) {
                    stat.setFastestDays(0);
                }
                if (stat.getSlowestDays() == null) {
                    stat.setSlowestDays(0);
                }
            });
        }
        result.setDesignerTimeStats(designerTimeStats != null ? designerTimeStats : Collections.emptyList());

        // 6. 设计师出图量统计
        List<Map<String, Object>> designerImageStatsMap = designStatisticsMapper.selectDesignerImageStats(query);
        List<DesignStatisticsVO.DesignerImageStatsVO> designerImageStats = new ArrayList<>();

        if (designerImageStatsMap != null && !designerImageStatsMap.isEmpty()) {
            // 转换为VO列表
            designerImageStats = designerImageStatsMap.stream().map(map -> {
                DesignStatisticsVO.DesignerImageStatsVO vo = new DesignStatisticsVO.DesignerImageStatsVO();
                vo.setDesignerId(((Number) map.get("designerId")).longValue());
                vo.setDesignerName((String) map.get("designerName"));
                vo.setTotalImageCount(((Number) map.get("totalImageCount")).intValue());
                vo.setSpaceImageCountMap(new HashMap<>());
                return vo;
            }).collect(Collectors.toList());

            // 获取空间维度出图量并合并
            List<Map<String, Object>> spaceImageStats = designStatisticsMapper.selectSpaceImageStats(query);
            if (spaceImageStats != null && !spaceImageStats.isEmpty()) {
                // 按设计师ID分组
                Map<Long, List<Map<String, Object>>> spaceStatsByDesigner = spaceImageStats.stream()
                        .collect(Collectors.groupingBy(m -> ((Number) m.get("designerId")).longValue()));

                // 合并到设计师统计中
                designerImageStats.forEach(designerStat -> {
                    List<Map<String, Object>> spaceStats = spaceStatsByDesigner.get(designerStat.getDesignerId());
                    if (spaceStats != null) {
                        Map<String, Integer> spaceMap = spaceStats.stream()
                                .collect(Collectors.toMap(
                                        m -> (String) m.get("spaceType"),
                                        m -> ((Number) m.get("imageCount")).intValue(),
                                        Integer::sum
                                ));
                        designerStat.setSpaceImageCountMap(spaceMap);
                    }
                });
            }
        }
        result.setDesignerImageStats(designerImageStats);

        // 7. 素材使用次数统计（按时间维度）
        List<Map<String, Object>> materialUsageList = designStatisticsMapper.selectMaterialUsageByTime(query);
        Map<String, Map<String, Integer>> materialUsageByTime = new LinkedHashMap<>();

        if (materialUsageList != null && !materialUsageList.isEmpty()) {
            // 按时间分组
            Map<String, List<Map<String, Object>>> usageByTime = materialUsageList.stream()
                    .collect(Collectors.groupingBy(m -> (String) m.get("timeKey")));

            // 构建结果结构
            usageByTime.forEach((timeKey, usageList) -> {
                Map<String, Integer> materialMap = usageList.stream()
                        .collect(Collectors.toMap(
                                m -> (String) m.get("materialName"),
                                m -> ((Number) m.get("usageCount")).intValue(),
                                Integer::sum
                        ));
                materialUsageByTime.put(timeKey, materialMap);
            });
        }
        result.setMaterialUsageByTime(materialUsageByTime);

        return result;
    }
}